<template>
	<view class="layout" v-if="DataFrom">
		<!-- 导航栏 -->
		<navgate-bar-vue :isBack="true" title=" 投票"></navgate-bar-vue>
		<view class="header">
			<view class="coverImage-box">
				<image class="image" :src="DataFrom.coverImage" mode="aspectFill"></image>
			</view>
			<view class="text-box">
				<view class="text">
					<view class="topic">
						{{DataFrom.topic}}
					</view>
					<view class="introduce">
						{{DataFrom.introduce}}
					</view>
					<view class="box">
						<view class="time-box">
							<view class="time">
								<view class="">
									开始时间
								</view>
								<view class="time-number">
									{{ formatTime(DataFrom.startTime) }}
								</view>
							</view>
							<view class="time">
								<view class="">
									结束时间
								</view>
								<view class="time-number">
									{{ formatTime(DataFrom.endTime) }}
								</view>
							</view>
						</view>
						<view class="active-btn">
							<view class="btn" @click="openVito" v-if="DataFrom.rankingStatus===1">加入活动</view>
							<view class="btn" @click="openComment">查看评论</view>
						</view>

					</view>
				</view>
			</view>
			<view class="line"></view>
		</view>
		<view class="table">
			<view class="table-header">
				<view class="table-cell" style="width: 10%;">排名</view>
				<view class="table-cell" style="width: 40%;">标题</view>
				<view class="table-cell" style="width: 20%;">封面图</view>
				<view class="table-cell" style="width: 10%;">票数</view>
				<view class="table-cell" style="width: 30%;">操作</view>
			</view>

			<view class="table-row" v-for="(item, index) in tableData" :key="item.id">
				<view class="table-cell" style="width: 10%;">{{ index + 1 }}</view>
				<view class="table-cell" style="width: 40%;">{{ item.topic }}</view>
				<view class="table-cell" style="width: 20%;">
					<image :src="item.coverImage" style="width: 60rpx; height: 60rpx;" />
				</view>
				<view class="table-cell" style="width: 10%;">{{ item.number }}</view>
				<view class="table-cell" style="width: 30%;">
					<view class="operate">
						<view @click="openDetails(item.id)">查看详情</view>
						<view @click="createVito(item.id)" v-if="DataFrom.rankingStatus===1">投票</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 详情弹框 -->
		<uni-popup ref="detailsPoup">
			<view class="details" v-if="popuData">
				<view class="title-details">
					{{popuData.topic}}
				</view>
				<view class="name-details">
					{{popuData.realName}}
				</view>
				<view class="introduce-details">
					{{popuData.introduce}}
				</view>
				<view class="image-details-box">
					<image class="image-details" :src="popuData.coverImage" mode="aspectFill"></image>
				</view>
			</view>
		</uni-popup>
		<!-- 加入活动弹框 -->
		<uni-popup ref="vitoPoup">
			<view class="vito-popu">
				<view class="vito-header">
					<view class="vito-title">标题</view>
					<input class="input-title" v-model="listData.topic" focus placeholder="请输入标题" />
				</view>
				<view class="image-box">
				<view class="vito-image">
					<view class="">
						封面图
					</view>
					<view class="login_img" @click="handleChooseImage">
						<uni-icons type="plusempty" size="30">
						<image class="coverImage" mode="aspectFill" :src="imageValue[0]?.url || ''" />
						<view v-if="uploading" class="upload-mask">上传中...</view>
						</uni-icons>
					</view>
					</view>
				</view>
				<view class="vito-introduce-box">
					<view class="vito-introduce">详情</view>
					<uni-easyinput type="textarea" v-model="listData.introduce" placeholder="请输入内容"></uni-easyinput>
				</view>
				<view class="vito-botton">
					<view class="vito-submint" @click="confirmSubmitVito ">提交</view>
					<view class="vito-cancel" @click="cancelVito">取消</view>
				</view>
			</view>
		</uni-popup>

		<!-- 评论弹框 -->
		<uni-popup ref="comments">
			<view class="comment-popu">
				<scroll-view class="comment-scroll" scroll-y>
					<view class="comment-box" v-for="item in CommentDate" :key="item">
						<view class="comment-layout">
							<image :src="item.avatarUrl" class="comments-image"  mode="aspectFill"></image>
							<view class="comment-nickname">
								{{item.nickname}}：
							</view>
							<view class="comment">
								{{item.content}}
							</view>
						</view>
						<view class="comment-time">
							{{ formatTime(item.createTime) }}
						</view>
						<view style="width: 100%; border: 1rpx solid #666;"></view>
					</view>
				</scroll-view>
				<view style="width: 100%; border: 1rpx solid #ccc ;"></view>
				<view class="comment-input">
					<uni-easyinput class="uni-mt-5" v-model="CommenList.content" placeholder="输入评论"></uni-easyinput>
					<view class="comment-btn" @click="createComment">
						提交
					</view>
				</view>
			</view>

		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		AppGetRankingDetialInfoApi,
		AppGetvitoInfoApi,
		AppGetReviewInfoApi,
		AppCreatReviewApi,
		AppCreatVitoApi,
	} from '@/api/vito';
	import {
		formatTime
	} from '@/utils/time';
	import {
		AppUploadFileApi
	} from "@/api/upload";

	import {
		AppGetCommentsAllApi,
		AppCreateCommentsApi
	} from '@/api/index';

	import {
		useUserStore
	} from '@/store';


	// 存储排行榜详情数据
	const DataFrom = ref(null);
	const id = ref(null);
	const vitoId = ref(null);
	const tableData = ref(null);

	const imageValue = ref([]);


	// 获取本地数据
	const userStore = useUserStore();
	//参加活动
	const listData = ref({
		topic: '',
		coverImage: '',
		introduce: '',
		userId: userStore.id,
		rankingId: ''
	})
	//进行投票
	const VitoData = ref({
		judgeId: '',
		userId: userStore.id,
		rankingId: ''
	})

	//详情弹框
	const detailsPoup = ref(false);
	const vitoPoup = ref(false);

	const openDetails = (itemId) => {
		if (detailsPoup.value) {
			detailsPoup.value.open('center');
			getReviewInfo(itemId);
		}
	};

	const openVito = () => {
		if (vitoPoup.value) {
			vitoPoup.value.open('center');
		}
	};

	//获取评论
	const comments = ref(false);
	const rankingId = ref(null);
	const CommentDate = ref(null);

	const openComment = () => {
		if (comments.value) {
			comments.value.open('center');
			getCommentslInfo();
			CommenList.value.content = '';
		}
	};

	const getCommentslInfo = async () => {
		if (!id.value) return;

		try {
			const response = await AppGetCommentsAllApi(rankingId.value);
			CommentDate.value = response.data;
		} catch (error) {
			uni.showToast({
				title: '获取数据失败，请稍后重试',
				icon: 'none'
			});
		}
	};
	//创建评论
	const CommenList = ref({
		content: '',
		userId: userStore.id,
		rankingId: ''
	})
	const createComment = async () => {
		try {
			const response = await AppCreateCommentsApi(CommenList.value);
			if (response.msg === 'success') {
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				});
				CommenList.value.content = '';
				getCommentslInfo();
			}
		} catch (error) {
			uni.showToast({
				title: '获取数据失败，请稍后重试',
				icon: 'none'
			});
		}
	};

	// 获取排行榜详情信息
	const getRankDetalInfo = async () => {
		if (!id.value) return;

		try {
			const response = await AppGetRankingDetialInfoApi(id.value);
			DataFrom.value = response.data[0];
			listData.value.rankingId = DataFrom.value.id;
			VitoData.value.rankingId = DataFrom.value.id;
			rankingId.value = DataFrom.value.id;
			CommenList.value.rankingId = DataFrom.value.id;
		} catch (error) {
			uni.showToast({
				title: '获取数据失败，请稍后重试',
				icon: 'none'
			});
		}
	};

	// 获取排行排名信息
	const getVitoInfo = async () => {
		if (!id.value) return;
		try {
			const response = await AppGetvitoInfoApi(id.value);
			tableData.value = response.data;
		} catch (error) {
			uni.showToast({
				title: '获取数据失败，请稍后重试',
				icon: 'none'
			});
		}
	};
	/**
	 * 获取排名详细信息
	 */
	const popuData = ref(null);
	const getReviewInfo = async (id) => {
		if (!id)
			return;
		try {
			const response = await AppGetReviewInfoApi(id);
			popuData.value = response.data[0];
		} catch (error) {
			uni.showToast({
				title: '获取数据失败，请稍后重试',
				icon: 'none'
			});
		}
	};


	// 页面加载时获取 id 并调用 API
	onLoad((options) => {
		if (options.id) {
			id.value = options.id;
			getRankDetalInfo();
			getVitoInfo();
		}
	});

	//确定按钮
	const confirmSubmitVito = () => {
		uni.showModal({
			title: '确认提交',
			content: '确定要提交该活动吗？',
			success: (res) => {
				if (res.confirm) {
					submitVito();
				}
			}
		});
	};
	const uploading = ref(false);

	// 图片选择与上传逻辑
	const handleChooseImage = async () => {
		try {
			const res = await uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera']
			});

			const tempFilePath = res.tempFilePaths[0];
			imageValue.value = [{
				url: tempFilePath
			}];

			uploading.value = true;
			const uploadRes = await AppUploadFileApi(tempFilePath);

			if (uploadRes && uploadRes.data && uploadRes.data) {
				listData.value.avatarUrl = uploadRes.data;
				uni.showToast({
					title: '封面图上传成功',
					icon: 'success'
				});
			} else {
				throw new Error("上传失败，请联管理员");
			}
		} catch (error) {
			uni.showToast({
				title: '上传失败，请重试',
				icon: 'none'
			});
			console.error('上传错误:', error);
		} finally {
			uploading.value = false;
		}
	};
	//加入活动
	const submitVito = async () => {
		if (!listData.value.topic || !listData.value.coverImage || !listData.value.introduce) {
			uni.showToast({
				title: '请填写完整信息',
				icon: 'none'
			});
			return;
		}

		try {
			const response = await AppCreatReviewApi(listData.value);
			if (response.code === 1) {
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				});
				resetForm(); // 提交成功后清空数据
				vitoPoup.value.close(); // 关闭弹窗
				getVitoInfo(); // 重新获取排行榜数据
			} else {
				uni.showToast({
					title: response.msg || '提交失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.showToast({
				title: '提交失败，请稍后重试',
				icon: 'none'
			});
		}
	};
	// 取消按钮，清空数据并关闭弹窗
	const cancelVito = () => {
		resetForm();
		vitoPoup.value.close();
	};
	// 重置表单数据
	const resetForm = () => {
		listData.value = {
			topic: '',
			coverImage: '',
			introduce: '',
			userId: userStore.id,
			rankingId: ''
		};
		imageValue.value = [];
	};
	//进行投票
	const createVito = (itemid) => {
		if (!itemid) {
			uni.showToast({
				title: '投票对象不存在',
				icon: 'none'
			});
			return;
		}

		uni.showModal({
			title: '确认投票',
			content: '确定要为该选手投票吗？',
			success: async (res) => {
				if (res.confirm) {
					await buttonVito(itemid);
				}
			}
		});
	};
	// 提交投票
	const buttonVito = async (itemid) => {
		VitoData.value.judgeId = itemid; // 设置投票对象 ID

		try {
			const response = await AppCreatVitoApi(VitoData.value);
			uni.showToast({
				title: response.code === 1 ? '投票成功' : response.msg || '投票失败',
				icon: response.code === 1 ? 'success' : 'none'
			});

			if (response.code === 1) {
				getVitoInfo(); // 重新获取排行榜数据
			}
		} catch (error) {
			uni.showToast({
				title: '投票失败，请稍后重试',
				icon: 'none'
			});
		}
	};
</script>

<style lang="scss" scoped>
	.layout {
		height: 100vh;
		background-color: #fff;
	}

	.coverImage-box {
		width: 100%;
	}

	.image {
		width: 100%;
		height: 300rpx;
	}

	.text-box {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.text {
		width: 700rpx;
		height: 300rpx;
	}

	.topic {
		height: 80rpx;
		font-weight: 700;
	}

	.introduce {
		font-size: 25rpx;
		color: #6e6e6e;
		height: 150rpx;
	}

	.box {
		display: flex;
	}

	.active-btn {
		width: 150rpx;
		height: 40rpx;
		margin-left: 150rpx;
	}

	.btn {
		font-size: 25rpx;
		color: #5aacfe;
		height: 100%;
	}

	.time {
		font-size: 25rpx;
		display: flex;
		color: #6e6e6e;
	}

	.time-number {
		margin-left: 20rpx;
	}

	.line {
		margin-top: 10rpx;
		width: 100%;
		border: 2rpx solid #ccc;
	}

	.table {
		width: 100%;
		font-size: 20rpx;
	}

	.table-header,
	.table-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx 0;
	}

	.table-cell {
		text-align: center;
		line-height: 40rpx;
	}

	.operate {
		display: flex;
		justify-content: space-around;
	}

	.details {
		width: 500rpx;
		height: 700rpx;
		border-radius: 10rpx;
		background: linear-gradient(to top, #a9c1f1, #f8c6ec);
	}

	.title-details {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 50rpx;
		font-size: 20rpx;
	}

	.name-details {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100rpx;
		margin: auto;
	}

	.introduce-details {
		margin: 20rpx auto;
		width: 80%;
		height: 150rpx;
		font-size: 20rpx;
	}

	.image-details-box {
		margin: auto;
		width: 300rpx;
		height: 300rpx;
	}

	.image-details {
		width: 100%;
		height: 100%;
	}

	.vito-popu {
		width: 700rpx;
		height: 50vh;
		background-color: #fff;
		border-radius: 15rpx;

		.vito-header {
			display: flex;
			align-items: center;
			padding: 10rpx;

			.input-title {
				border: 1rpx solid #ccc;
				margin-left: 20rpx;
			}

			.vito-title {
				margin-left: 10rpx;
			}
		}
		.image-box{
			display: flex;
			align-items: center;
		}

		.vito-image {
			width: 100%;
			height: 300rpx;
			margin-top: 50rpx;
			margin-left: 20rpx;
			display: flex;

			.coverImage {
				width: 200rpx;
				height: 200rpx;
			}

			.login_img {
				width: 200rpx;
				height: 200rpx;
			}
		}

		.vito-introduce-box {
			display: flex;

			.vito-introduce {
				margin-left: 10rpx;
			}

			.vito-introduce-input {
				margin-left: 10rpx;
			}
		}

		.vito-botton {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 50rpx;

			.vito-cancel {
				margin-left: 50rpx;
			}
		}
	}

	.comment-popu {
		height: 60vh;
		width: 600rpx;
		background-color: #fff;
		border-radius: 15rpx;

		.comment-scroll {
			height: 70%;
			width: 550rpx;
			margin: auto;
			padding-top: 20rpx;
		}

		.comment-layout {
			display: flex;
			margin-top: 20rpx;
		}

		.comment-nickname {
			margin-left: 20rpx;
			font-size: 20rpx;
		}

		.comments-image {
			width: 50rpx;
			height: 50rpx;
			border-radius: 50rpx;
		}

		.comment-time {
			font-size: 15rpx;
			margin-left: 400rpx;
			color: #999;
		}

		.comment {
			margin-left: 20rpx;
			width: 400rpx;
			font-size: 20rpx
		}

		.comment-input {
			padding-top: 20rpx;
			margin: auto;
			width: 500rpx !important;
		}

		.comment-btn {
			margin-top: 20rpx;
			color: #5aacfe;
		}

	}
</style>